<?php

require_once realpath (dirname (__FILE__) . '//..//pages.php');
require_once INC_FUNCTIONS;
require_once MDL_ACTIONS;
require_once MDL_TABLES;

function generatePermissions () {
    $actions = array_keys (getActions ());
    $tables = array_keys (getTables ());
    $db = openConnection ();

    foreach ($actions as $action) {
        foreach ($tables as $table) {
            if ($db->insert ('permesso', array ('action' => $action, 'what' => $table), true)) {
                echo ' Successful!<br>';
            } else {
                echo ' Failed!<br>';
            }
        }
    }
}

function assign ($profile, $IDuser) {
    $profiles = array (
        'admin' => array (
            'delete' => array ('all'),
            'edit' => array ('all'),
            'insert' => array ('all'),
            'view' => array ('all')
        ),
        'deleter' => array (
            'delete' => array ('all')
        ),
        'editor' => array (
            'edit' => array ('all')
        )
    );
    $db = openConnection (true);
    foreach ($profiles[$profile] as $action => $tables) {
        $where = "permesso.action='$action'";
        $AND = true;
        foreach ($tables as $table) {
            if ($table == 'all') {
                break;
            } else {
                if ($AND) {
                    $AND = false;
                    $where .= ' AND (';
                }
                $where .= "permesso.what='$table' OR ";
            }
        }
        if (!$AND) {
            $where = substr ($where, 0, strlen($where) - 3);
            $where .= ')';
        }
        echo $where;
        $result = $db->select ('permesso', 'ID', $where);
        while ($row = $db->fetchAssoc ($result)) {
            $db->insert ('possiede', array ('IDuser' => $IDuser, 'IDpermesso' => $row['ID']));
        }
        break;
    }
}

if (isset ($_GET['generate'])) {
    generatePermissions ();
}
if (isset ($_GET['user']) && isset ($_GET['profile'])) {
    assign ($_GET['profile'], $_GET['user']);
}
?>
